package com.boyicloud.exchangeserver.netty.handler

import com.boyicloud.exchangeserver.common.DataBase
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component

@Component
@ChannelHandler.Sharable
class ExchangeHandler : SimpleChannelInboundHandler<ByteBuf>() {

    val log: Logger = LoggerFactory.getLogger(ExchangeHandler::class.java)

    override fun channelRead0(ctx: ChannelHandlerContext, message: ByteBuf) {

        val len = message.readableBytes()
        var equipment = DataBase.equipmentListMap[ctx.channel().id()]
        equipment?.let { it.txBytes += (len.toDouble() / 1024 / 1024) }
        val channel = DataBase.penetrateMap[ctx.channel().id()]
        channel?.let {
            val bytes = ByteArray(len)
            message.readBytes(bytes)
            channel.writeAndFlush(Unpooled.copiedBuffer(bytes))
            equipment = DataBase.equipmentListMap[channel.id()]
            equipment?.let { i -> i.rxBytes += (len.toDouble() / 1024 / 1024) }
        }
    }
}
